import {useStore} from "vuex";
import {computed, toRefs} from "vue";

export const useCommonCartEffect = (shopId) => {
  const store = useStore();
  //store里的数据 vuex会帮我们自动转换为reactive的
  const cartList = store.state.cartList
  const changeCartItemInfo = (shopId, productId, productInfo, num) => {
    // console.log('changeCartItemInfo shopId,productId,productInfo:',shopId,productId,productInfo)
    store.commit('changeCartItemInfo', {shopId, productId, productInfo, num})
  };

  const productList = computed(()=>{
    const productList = cartList[shopId]?.productList || [];
    const notEmptyProductList = {};
    for (let i in productList) {
      const product = productList[i];
      if (product.count > 0) {
        notEmptyProductList[i] = product;
      }
    }
    //console.log('notEmptyProductList:',notEmptyProductList)
    return notEmptyProductList;
  })

  const shopName = computed(()=>{
    const shopName = cartList[shopId]?.shopName || '';
    return shopName;
  })

  const calculations = computed(() => {
    const productList = cartList[shopId]?.productList;
    const result = {total: 0, price: 0, allChecked: true};

    if (productList) {
      for (const i in productList) {
        const product = productList[i];
        result.total += product.count;
        if(product.check) result.price += (product.count * product.price);
        if(product.count > 0 && !product.check){
          result.allChecked = false;
        }
      }
    }
    result.price = result.price.toFixed(2);

    return result;
  });

  return {cartList, productList, shopName, calculations, changeCartItemInfo};
};
